# coding=utf-8
# author: huhai
# date: 27/04/2015 12:09:36
import os
import sys
import uuid
import datetime

BASE_DIR = os.path.dirname(os.path.dirname(__file__))

try:
    from lib import xlrd, xlwt
except:
    LIB_PATH = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'lib')
    if not LIB_PATH in sys.path:
        sys.path.insert(0, LIB_PATH)
    # print sys.path
    import xlrd, xlwt


def parse_xls(sheet):
    ret = []
    for i in xrange(1, sheet.nrows):
        row = sheet.row_values(i)
        if len(row) < 1:
            continue
        if row[0] == '':
            continue
        if not isinstance(row[0], int):
            sequence = int(row[0])
        else:
            sequence = row[0]
        for j in range(1, 8):
            if row[j] == '':
                continue
            lesson_name = row[j]
            weekday = models.WEEK_KEYS[j - 1][0]
            lesson_schedule = {
                'row': i + 1,
                'column': j + 1,
                'lesson_period_sequence': sequence,
                'weekday': weekday,
                'lesson_name': lesson_name
            }
            if not verify:
                lesson_schedule['class_uuid'] = c.uuid
            ret.append(lesson_schedule)
    
    return ret



def read_xls(fpath, *args, **kwargs):
    if not os.path.isabs(fpath):
        fpath = os.path.join(BASE_DIR, tmp_file_id) + '.xls'
    with open(fpath, 'r') as excel:
        data = f.read()
        xls = xlrd.open_workbook(file_contents=data)
        sheet = xls.sheet_by_index(0)

def write_xls(xls_header, keys, data):
    # tmp_file_id = str(uuid.uuid1())
    tmp_file_id = datetime.datetime.now().strftime('%Y%m%d-%H%M%S-%f')
    tmp_file = os.path.join(BASE_DIR, tmp_file_id)
    tmp_file += '.xls'
    xls = xlwt.Workbook(encoding='utf8')
    sheet = xls.add_sheet('export')

    for i, v in enumerate(xls_header):
        sheet.write(0, i, v)

    row = 1
    for d in data:
        for i, k in enumerate(keys):
            sheet.write(row, i, d.get(k, ''))
        row += 1
    xls.save(tmp_file)
    print 'file saved at:', tmp_file


def test():
    xls_header = ('A', 'B', 'c')
    keys = ('aa', 'bb', 'cc')
    data = [
        {'aa': 1, 'bb': 2, 'cc': 3},
        {'aa': 4, 'bb': 5, 'cc': 6},
        {'aa': 7, 'bb': 8, 'cc': 9},
    ]
    write_xls(xls_header, keys, data)

if __name__ == '__main__':
    test()